package com.cheejee.service.oss.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.multipart.MultipartFile;

import com.carry.common.file.FileName;
import com.cheejee.oss.dao.StorageMapper;
import com.cheejee.oss.entity.Storage;
import com.cheejee.oss.service.StorageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @author CARRY
 * @Date 2020年11月6日上午6:17:46
 */
public class LocalStorageServiceImpl implements StorageService {

	public static final Integer LOCAL_STORATE_TYPE = 1;

	@Resource
	private StorageMapper mapper;

	private String absolutePath;
	private String relativePath;

	public LocalStorageServiceImpl(String absolutePath, String relativePath) {
		this.absolutePath = absolutePath;
		this.relativePath = relativePath;
	}

	@Override
	public PageInfo<Storage> query(Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<Storage>(mapper.selectByType(LOCAL_STORATE_TYPE));
	}

	@Override
	public String upload(MultipartFile file) throws IOException {
		String fileName = FileName.builder(file.getOriginalFilename());
		File f = new File(absolutePath + "/" + fileName);
		file.transferTo(f);
		String url = relativePath + fileName;
		Storage s = new Storage(null, fileName, url, file.getSize(), LOCAL_STORATE_TYPE, new Date());
		mapper.insert(s);

		return url;
	}

	@Override
	public void delete(Long[] id) throws IOException {
		List<String> lk = mapper.selectKey(id);
		for (String i : lk) {
			File file = new File(absolutePath + i);
			Files.delete(file.toPath());
		}
	}
}
